﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebProjectOrder.WebServices;
using WebProjectOrder.BusinessLayer;

namespace WebProjectOrder.Presentation
{
    public partial class BuyOrder : System.Web.UI.Page
    {
        private int[] _storeRoomIds;
        private int[] _taxIds;
        private AuxiliarAccount AccountSelected =  ConfigurationManager.GetInstance().AccountSelected;
        protected void Page_Load(object sender, EventArgs e)
        {
            DocumentManager.GetInstance().itemsDocuments.Clear();
            if (!IsPostBack)
            {
                lblCodCliente1.Text = AccountSelected.AccountCode.ToString();
                lblNombreCliente1.Text = AccountSelected.OwnerName;
                lblCuentaAux1.Text = AccountSelected.Name;
                fillDropListCurrencies();
                fillDropListStores();
                fillDropListTax();
                fillDropListArticle();                
            }
            

        }

        //Método para llenar todas las monedas de un comboBox
        public void fillDropListCurrencies() 
        {
            drpListCurrency.Items.Clear();
            List<Currency> currencies = CurrencyManager.getInstance().GetCurrencies();
            foreach (Currency currency in currencies)
                drpListCurrency.Items.Add(currency.Name);
        }

        // Llenar el combobox de todas las bodegas
        private void fillDropListStores()
        {
            drpListStore.Items.Clear();
            List<StoreRoom> stores = StoreRoomManager.GetInstance().GetStoreRooms();
            _storeRoomIds = new int[stores.Count];
            int srIndex = 0;
            if (!StoreRoomManager.GetInstance().IsError)
                foreach (StoreRoom store in stores)
                {
                    drpListStore.Items.Add(store.Name);
                    _storeRoomIds[srIndex++] = store.Id;
                }
            else
            {
                //Aqui se ponen los casos donde no se puede cargar las bodegas
            }
            if (srIndex > 0) drpListStore.SelectedIndex = 0;
        }

        //Encontrar el Id Real
        private int findIdStores(int idFalso)
        {
            List<StoreRoom> bodegas = StoreRoomManager.GetInstance().GetStoreRooms();
            return bodegas[idFalso].Id;
            
        }

        //Llenar el comboBox de todos los artículos por bodegas
        private void fillDropListArticle()
        {
            drpListDesc.Items.Clear();
            int idStore = findIdStores(drpListStore.SelectedIndex);
            List<StoreItem> articulosxBodegas = ItemManager.GetInstance().GetStoreItem(idStore);
            int largoArticulosxBodegas = articulosxBodegas.Count;

            for (int i = 0; i < largoArticulosxBodegas; i++) 
            {
                drpListDesc.Items.Add(articulosxBodegas[i].Descripcion);
            }
        }


        //Llenar el comboBos de todas los impuestos
        private void fillDropListTax() 
        {
            drpListTax.Items.Clear();
            List<Tax> impuestos = ConfigurationManager.GetInstance().GetTaxes();
            _taxIds = new int[impuestos.Count];
            int taxIndex = 0;
            if (!StoreRoomManager.GetInstance().IsError)
            {
                foreach (Tax impuesto in impuestos)
                {
                    drpListTax.Items.Add(impuesto.Nombre);
                    _taxIds[taxIndex++] = impuesto.IdImpuesto;
                }
            }
            else
            {
                // Aqui se pone el caso donde no se pueden cargar los impuestos
            }
            if (taxIndex > 0) drpListTax.SelectedIndex = 0;
        }

        //Metodo para encontrar el id del articulo
        public int findIdItem(int idStore, String description)
        {
            int idItem = 0;
            List<StoreItem> ItemsxStore = ItemManager.GetInstance().GetStoreItem(idStore);
            foreach(StoreItem itemsStore in ItemsxStore)
            {
                if(itemsStore.Descripcion.Equals(description))
                {
                    idItem = itemsStore.IdArticulo;
                }else{}
            }
            return idItem;
        }


        //Método para encontrar el id del impuesto
        public int findIdTax(int idTaxFalse) 
        {
            List<Tax> impuestos = ConfigurationManager.GetInstance().GetTaxes();
            return impuestos[idTaxFalse].IdImpuesto;
        }
        //Valida el Stock
        public bool validarStock()
        {
            int idStore = findIdStores(drpListStore.SelectedIndex);
            List<StoreItem> ItemsxStore = ItemManager.GetInstance().GetStoreItem(idStore);
            bool boolean = true;
            int iditem = findIdItem(idStore, drpListDesc.Text);
            int amount = int.Parse(txtCant.Text);
            foreach (StoreItem storeItem in ItemsxStore)
            {
                if ((storeItem.Stock < amount) && (iditem == storeItem.IdArticulo))
                {
                    txtCant.Text = "";
                    lblItem.Text = "No existe esa cantidad de Artículos";
                    boolean = false;
                    return boolean;
                }
                else { lblItem.Text = ""; }
            }
            return boolean;
        }
        //Valida info del articulo
        public bool validarAmount() 
        {
            try
            {
                
                int.Parse(txtCant.Text);
                if (validarStock()) 
                {
                    return true;
                }
                return false;
            }
            catch
            {
                txtCant.Text = "";
                lblCant.Text = "*";
                return false;
            }
        }

        //Método para guardar un articulo en una Lista
        public void saveArticle()
        {
            if (validarAmount())
            {
                int idStore = findIdStores(drpListStore.SelectedIndex);
                int idItem = findIdItem(idStore, drpListDesc.Text);
                String description = drpListDesc.Text;
                int amount = int.Parse(txtCant.Text);
                int idTax = findIdTax(drpListTax.SelectedIndex);
                ItemDocument itemDoc = new ItemDocument(Constants.INVALID_ID, idStore, idItem, description, amount, 0, idTax);
                DocumentManager.GetInstance().itemsDocuments.Add(itemDoc);
                /***********************************************************************/
                String Bodega = drpListStore.Text;
                String Descripcion = drpListDesc.Text;
                int Cantidad = int.Parse(txtCant.Text);
                String Impuesto = drpListTax.Text;
                ItemMask itemMask = new ItemMask(Bodega, Descripcion, Cantidad, Impuesto);
                DocumentManager.GetInstance().itemMasks.Add(itemMask);
                /**********************************************************************/
                List<ItemMask> newList = DocumentManager.GetInstance().itemMasks;
                this.gv.DataSource = newList;
                this.gv.DataBind();
            }
            else { }
            
        }
        //Método para buscar el id de la moneda seleccionada
        public int findIdCurrency(int idCurrencyFalse) 
        {
            List<Currency> currencyList = CurrencyManager.getInstance().GetCurrencies();
            return currencyList[idCurrencyFalse].Id;
        }

        //Método para guardar un documento
        public void saveDocument() 
        {
            String DocType = "OC";
            int idAuxAccount = ConfigurationManager.GetInstance().AccountSelected.AccountID;
            DateTime PostingDate = DtPckrPosting.SelectedDate;
            DateTime DeliveryDate = DtPckrDelivery.SelectedDate;
            int idCurrency = findIdCurrency(drpListCurrency.SelectedIndex);
            Double AmountBeforeTax = 0;
            Double TaxAmount = 0;
            Double TotalAmount = 0;
            Document Document = new Document(DocType, idAuxAccount, PostingDate, DeliveryDate, idCurrency, 0, AmountBeforeTax, TaxAmount, TotalAmount);
            Document = DocumentManager.GetInstance().newDocument;

        }




        /**************************************************************************************/
        protected void GridViewItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            

        }

        protected void DatePicker1_SelectionChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            
        }

        protected void gv_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnAgregarItem_Click(object sender, EventArgs e)
        {
            saveArticle();
        }

        protected void drpListStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            fillDropListArticle();
        }

        protected void drpListDesc_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        protected void btnAgregarDoc_Click(object sender, EventArgs e)
        {
          //  saveDocument();
        }
    }
}